package com.devin.util;

import cn.hutool.core.util.URLUtil;
import com.devin.exception.NotFoundException;
import com.devin.model.constant.VPartyConst;
import com.devin.model.entity.BiliVideo;
import com.devin.repository.BilibiliRepository;
import jdk.nashorn.internal.runtime.options.Option;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 *  @author devin
 *  @date 2020-04-11 12:14
 *  @version 1.0.2
 */

@Slf4j
public class BilibiliUtil {

    @Autowired
    private BilibiliRepository bilibiliRepository;

    public static Optional<BiliVideo> getVideo(String biliUrl) throws IOException {
        boolean httpUrl = StringUtil.isHttpUrl(biliUrl);
        if(!httpUrl){
            log.info("你输入的网址有误");
            return Optional.empty();
        }
        Document biliDocument = Jsoup.connect(biliUrl).get();
        String title = biliDocument.title();
        String des = biliDocument.select("#v_desc > div").first().text();
        String up = biliDocument.select("#v_upinfo > div.u-info > div.name > a.username").text();
        String face = biliDocument.select("head > meta:nth-child(12)").attr("content");
//        System.out.println(face);
//        开始视频解析
        Document document = Jsoup.connect(VPartyConst.BiliAPi + biliUrl).get();
        Element select = document.select("iframe").first();
        String newsrc = select.attr("src");
        //二次解析获得视频的文档
        Document src = Jsoup.connect(newsrc).get();
        Element scripts = src.select("body > script:nth-child(5)").first();

        Pattern pattern = Pattern.compile("http:[^\\s]*[0-9]");
        Matcher matcher = pattern.matcher(scripts.toString());
//        System.out.println(scripts);
        String url = null;
        if(matcher.find()){
//            System.out.println(matcher.group(0));
            url = matcher.group(0);
        }

        BiliVideo biliVideo = new BiliVideo(title, up, des, url,face,biliUrl);
        Optional<BiliVideo> optional = Optional.ofNullable(biliVideo);
        return optional;
    }

    @Test
    public void test(){
        BiliVideo video = null;
        try {
            video = getVideo("https://www.bilibili.com/video/BV11g4y187UQ").get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(video.toString());
//        bilibiliRepository.save(video);

    }
}